package com.sinosoft.dsp.platform.components.system;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.event.CloseEvent;
import org.primefaces.event.DashboardReorderEvent;
import org.primefaces.model.DashboardColumn;
import org.primefaces.model.DashboardModel;
import org.primefaces.model.DefaultDashboardColumn;
import org.primefaces.model.DefaultDashboardModel;

import com.sinosoft.dsp.platform.components.IViewBean;
import com.sinosoft.dsp.platform.components.ViewListBean;
import com.sinosoft.dsp.system.utils.Const;

/**
 * Home页ViewBean
 * 
 * @author 潘巍（Peter Pan）
 * @since 2010-10-26 上午06:10:04
 */
public class HomeViewListBean extends ViewListBean implements Serializable,
		IHomeViewListBean {

	private static final long serialVersionUID = 7999900476448099341L;

	private int moduleColumn = Const.CONST_MAINVIEW_TAB_HOME_MODULESET_COLUMN;

	private DashboardModel model;

	@Override
	public void handleReorder(DashboardReorderEvent event) {
		FacesMessage message = new FacesMessage();
		message.setSeverity(FacesMessage.SEVERITY_INFO);
		message.setSummary("Reordered: " + event.getWidgetId());
		message.setDetail("Item index: " + event.getItemIndex()
				+ ", Column index: " + event.getColumnIndex()
				+ ", Sender index: " + event.getSenderColumnIndex());
		addMessage(message);
	}

	@Override
	public void handleClose(CloseEvent event) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Panel Closed", "Closed panel id:'"
						+ event.getComponent().getId() + "'");
		addMessage(message);
	}

	private void addMessage(FacesMessage message) {
		FacesContext.getCurrentInstance().addMessage(null, message);
	}

	@Override
	public DashboardModel getModel() {
		if (model == null) {
			init();
		}
		return model;
	}

	private void init() {
		model = new DefaultDashboardModel();
		DashboardColumn[] cols = new DashboardColumn[moduleColumn];
		for (int i = 0; i < moduleColumn; i++) {
			cols[i] = new DefaultDashboardColumn();
		}

		// TODO
		List<IViewBean> views = this.getAllView();
		if (views != null)
			for (int i = 0; i < views.size(); i++) {
				cols[i % moduleColumn].addWidget(views.get(i).getId());
			}

		for (int i = 0; i < moduleColumn; i++) {
			model.addColumn(cols[i]);
		}
	}

	@Override
	public int getModuleColumn() {
		return moduleColumn;
	}

	@Override
	public void setModuleColumn(int moduleColumn) {
		this.moduleColumn = moduleColumn;
	}

}
